package com.ruoyi.api.controller;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.ruoyi.api.domain.*;
import com.ruoyi.api.param.SuggestParam;
import com.ruoyi.api.repository.GuidCateGoriesRepository;
import com.ruoyi.api.repository.GuidRegionRepository;
import com.ruoyi.api.service.*;
import com.ruoyi.api.vo.GuidVo;
import com.ruoyi.common.annotation.RequiresLogin;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
public class GuidController {

    @Autowired
    private GuidService guidService;
    @Autowired
    private UserGuidService userGuidService;
    @Autowired
    private GuidRegionRepository guidRegionRepository;

    @Autowired
    private GuidCateGoriesRepository guidCateGoriesRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private GuidDayScenicService guidDayScenicService;

    @Autowired
    private UserEmailService userEmailService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private UserService userService;
    /**
     * 列表
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @GetMapping("/front/guidList")
    public Page<GuidEntity> guidList(GuidEntity loginBody,
                                     @RequestParam(required = false,name = "categorieList") String categorieList,
                                     @RequestParam(required = false,name = "where") String where,
                                     @RequestParam(required = true,name = "page") int page,
                                     @RequestParam(required = true,name = "size") int size)
            throws IllegalAccessException {
        // 根据景点id获取相关旅行计划
        List<ObjectId> list = new ArrayList<>();
        if(null!=where){
            List<String> stringList = Arrays.asList(where.trim().split(","));
            List<String> guidIds = guidDayScenicService.selectGuidIdByScenicId(stringList);
             list  = StringUtils.StringToObjectId(guidIds);
            loginBody.setGuidIdList(list);
        }
        if(null!=categorieList && !categorieList.isEmpty()){
            List<String> guidIds = guidService.selectGuidByCate(Arrays.asList(categorieList.split(",")));
            if (null!=guidIds){
                List<ObjectId> stringToObjectId = StringUtils.StringToObjectId(guidIds);
                list.addAll(stringToObjectId);
            }
            loginBody.setGuidIdList(list);
        }



        Page<GuidEntity> entities = guidService.selectList(GuidEntity.class,loginBody,page,size,mongoTemplate);
        return entities;
    }
    /**
     * 列表
     *
     * @return 结果
     */
    @GetMapping("/front/inspiredguidList")
    public List<GuidEntity> inspiredguidList(@RequestParam(required = false,name = "checkList") String check,@RequestParam(required = false,name = "where") String where) throws IllegalAccessException {
        // 根据地点区域
        List<ObjectId> guidIdList = new ArrayList<>();
//        if (where != null) {
//            List<String> guidIds = guidDayScenicService.selectGuidIdByScenicId(where);
//            guidIdList = StringUtils.StringToObjectId(guidIds);
//
//        }

        // 如果没有提供check参数(选中的类型)或者为空，则返回所有相关的旅行计划
        if (check != null ) {
            List<String> guidIds = guidService.selectGuidByCate(Arrays.asList(check.split(",")));
            if (null!=guidIds){
                List<ObjectId> stringToObjectId = StringUtils.StringToObjectId(guidIds);
                guidIdList.addAll(stringToObjectId);
            }

        }

        // 创建一个Criteria列表，用于存储每个模糊查询条件
        List<Criteria> criteriaList = new ArrayList<>();

        // 如果guidIdList不为空，则添加到查询条件中
        if (!guidIdList.isEmpty()) {
            Criteria guidIdCriteria = Criteria.where("_id").in(guidIdList);
            criteriaList.add(guidIdCriteria);
        }

        // 将Criteria列表合并到一个$and操作符中（如果需要所有条件都满足）
        // 或者如果需要满足任一条件，可以使用$or操作符（如原代码所示）
        Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[0]));

        // 创建查询对象
        Query query = new Query(criteria);

        // 执行查询
        return mongoTemplate.find(query, GuidEntity.class);

    }
    /**
     * 我的计划列表
     *
     * @param  guidEntity 详情
     * @return 结果
     */
    @GetMapping("/front/userGuidDel")
    @RequiresLogin
    public AjaxResult userGuidDel(GuidEntity guidEntity)  {

        DeleteResult entities  = guidService.deleteById(GuidEntity.class,guidEntity.getId(),mongoTemplate);

        return AjaxResult.success(entities);
    }
    /**
     * 我的计划列表
     *
     * @param  guidEntity 详情
     * @return 结果
     */
    @GetMapping("/front/userGuidList")
    @RequiresLogin
    public Page<UserGuidEntity> userGuidList(UserGuidEntity guidEntity,@RequestParam(required = true,name = "page") int page, @RequestParam(required = true,name = "size") int size) throws IllegalAccessException {
        UserEntity user = (UserEntity) request.getAttribute("user");

        UserGuidEntity userGuidEntity = new UserGuidEntity();
        userGuidEntity.setUserId(user.getId());
        userGuidEntity.setType(guidEntity.getType());
        Page<UserGuidEntity> entities  = userGuidService.selectList(UserGuidEntity.class,userGuidEntity,page,size,mongoTemplate);

        return entities;
    }

    /**
     * 详情
     *
     * @param loginBody 详情
     * @return 结果
     */
    @GetMapping("/front/guid")
    @RequiresLogin
    public AjaxResult guid(GuidEntity loginBody) throws IllegalAccessException {

        GuidEntity guidEntity = guidService.getInfoById(GuidEntity.class,loginBody.getId(),mongoTemplate);
        GuidVo guidVo = guidService.setPlans(guidEntity);

        return AjaxResult.success(guidVo);
    }
    /**
     * 保存我的计划
     *
     * @return 结果
     */
    @PostMapping("/front/addUserGuid")
    @RequiresLogin
    public AjaxResult addUserGuid(@RequestBody GuidEntity guidEntity) {
        UserEntity user = (UserEntity) request.getAttribute("user");

        guidEntity.setCreateBy(user.getEmail());
        guidEntity.setAttribute(user.getEmail());
        boolean res =  guidService.update(GuidEntity.class,guidEntity,mongoTemplate);
        if(!guidEntity.getPlans().isEmpty()){
            userGuidService.savePlans(guidEntity);
        }

        return AjaxResult.success(guidEntity);
    }

    /**
     * 保存我的计划
     *
     * @return 结果
     */
    @PostMapping("/front/rename")
    @RequiresLogin
    public AjaxResult rename(@RequestBody GuidEntity guidEntity) {
        Query query = new Query(Criteria.where("_id").is(new ObjectId(guidEntity.getId())));
        Update update = new Update().set("title", guidEntity.getTitle());
        UpdateResult result =  mongoTemplate.updateFirst(query, update, "guid");
        return AjaxResult.success(result);
    }


    /**
     * 验证是否有进行中的旅行指南
     *
     * @return 结果
     */
    @GetMapping("/front/checkGuid")
    @RequiresLogin
    public List<UserGuidEntity> checkGuid(String type) {
        UserEntity user = (UserEntity) request.getAttribute("user");
        //查询算法
        List<UserGuidEntity> entities = guidService.checkGuid(user,type);
        return entities;
    }


    /**
     * 旅行攻略推荐查询
     *
     * @param suggestParam 查询条件
     * @return 结果
     */
    @RequiresLogin
    @PostMapping("/front/suggestGuid")
    public List<GuidEntity> suggestGuid(SuggestParam suggestParam) {
        UserEntity user = (UserEntity) request.getAttribute("user");
        //查询算法
        List<GuidEntity> entities = guidService.selectAll();
        return entities;
    }

    /**
     * 获取区域
     *
     * @return 结果
     */
    @GetMapping("/front/region")
    public List<GuidRegionEntity> region() {
        //查询算法
        List<GuidRegionEntity> entities = guidRegionRepository.findAll();
        return entities;
    }
    /**
     * 获取类型
     *
     * @return 结果
     */
    @GetMapping("/front/categories")
    public List<GuidCateGoriesEntity> categories() {
        //查询算法
        List<GuidCateGoriesEntity> entities = guidCateGoriesRepository.findAll();
        return entities;
    }

    /**
     * 获取类型
     *
     * @return 结果
     */
    @PostMapping("/front/addUserEmail")
    public AjaxResult addUserEmail(@RequestBody UserEmailEntity userEmailEntity) {
        //查询算法
        UserEmailEntity entities = userEmailService.selectOne(UserEmailEntity.class,userEmailEntity,mongoTemplate);
        if(null != entities){
            return AjaxResult.error("");
        }
        userEmailService.update(UserEmailEntity.class,userEmailEntity,mongoTemplate);
        return AjaxResult.success();
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/front/avatarEdit")
    @RequiresLogin
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        UserEntity user = (UserEntity) request.getAttribute("user");
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            user.setAvatar(url);
            userService.updateAvatar(user);

            return AjaxResult.success(user);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}